<script setup lang="ts">
import { getCurrentMenuListToCascaderOption } from '@/api';
import { ElMessage, CascaderOption, CascaderProps, CascaderValue } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import CustomCascader from './custom-cascader.vue'

const prop = withDefaults(defineProps<{
  // 应用code
  application?: string,
  modelValue: CascaderValue,
  placeholder?: string,
  props?: CascaderProps,
  showAllLevels?: boolean,
  // 是否可清除
  clearable?: boolean,
  // 需要过滤的菜单类型
  filterType?: string | (string[])
  [p: string]: any,
  options?: CascaderOption[]
}>(), {
  props: {
    checkStrictly: true,
    // emitPath: false,
    expandTrigger: 'hover',
  },
  showAllLevels: false,
  clearable: true,
  placeholder: '请选择菜单',
  filterType: ''
})
const emit = defineEmits<{
  (t: 'update:modelValue', v: string): void
}>()
const fatherMenu = ref<CascaderOption[]>()

// 当选择的应用改变时
function appChange(application: string) {
  if (prop.options) return fatherMenu.value = prop.options
  if (!application) return (fatherMenu.value = []);
  getCurrentMenuListToCascaderOption(application, prop.filterType).then((data) => {
    data.unshift({label:'顶级菜单',value:'0'})
    fatherMenu.value = data;
  }, e => ElMessage.error("获取菜单列表出错！" + e));
}
watch(() => prop.application, appChange)
onMounted(() => {
  if (prop.application) {
    appChange(prop.application)
  }
})

</script>
<template>
  <CustomCascader :props="props" :clearable="clearable" :showAllLevels="showAllLevels" :placeholder="placeholder"
    v-bind="$attrs" :options="fatherMenu" :model-value="modelValue"
    @update:model-value="(e) => emit('update:modelValue', e)" />
</template>